var CatLoader={
	init:function(){
		var self = this;
		$("#nextBtn").attr("disabled",true);
		this.loadChildren();
		
		$("#nextBtn").click(function(){
			var catid  = self.getSelectedCatId();
			var catName = self.getSelectedCatName();
			if(!catid){
				alert("请选择商品的分类");
			}else{
				location.href = path + "/product/goods/form?goodsCat.id="+catid+"&catName="+catName ;
			}
		});
	},
	loadChildren:function(catid){
		var self = this;
		$.ajax({
			url:'/product/goodsCat/treeTableData', 
			data : {
                "id" :  catid
            },
			dataType:'json',
			success:function(result){
				if(!catid)catid=0;
				self.appendCatList(result,catid);
				self.refreshPath();
			},
			error:function(){
				alert("加载分类出错");
			}
		});
	},
	appendCatList:function(catJson,catid){
		if(catJson.length==0) return ;
		var self= this;
		var selHtml ="<div class='col-xs-3' id='box_"+catid+"'>";
		selHtml += "<div class='panel panel-default'>" ;
		selHtml += "<div class='panel-body'>";
		$.each(catJson,function(i,cat){
			selHtml+="<li catid="+cat.id+">";
			selHtml+=cat.name;
			selHtml+="</li>";
		});
		selHtml+="</div>";
		selHtml+="</div>";
		selHtml+="</div>";
		$(selHtml).appendTo( $("#cat-container") )
		.find("li").click(function(){
			var $this= $(this);
			self.removeChildBox( $this.parent().parent().parent().attr("id")  );
			self.loadChildren($this.attr("catid"));
			
			$this.siblings().removeClass("selected");
			$this.addClass("selected");
			
			$("#nextBtn").attr("disabled",false);
		});
	},
	removeChildBox:function(boxid){
		var flag= false;
		$("#cat-container .col-xs-3").each(function(){
			var $this= $(this);
			if(flag){
				$this.remove();
			}
			if($this.attr("id")== boxid){
				flag = true;
			}
		});
	},
	refreshPath:function(){
		var pathbox =$(".panel-footer .category-path").empty();
		var html ="";
		$("#cat-container li.selected").each(function(i,v){
			if(i!=0) html+=" > ";
			var name = $(this).text();
			html+=(""+name+""); 
		});
		pathbox.append(html);
	},
	getSelectedCatId:function(){
		var catEl=  $("#cat-container li.selected:last");
		if(catEl.length==0){
			return false;
		}else{
			return catEl.attr("catid");
		}
	},
	getSelectedCatName:function(){
		var pathbox =$(".panel-footer .category-path").text();
		if(pathbox) return pathbox;
		return "";
	}
};
$(function(){
	CatLoader.init();
});
